package com.lovi.net_.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * UDP接收端9999
 * 接收发送端发过来的话，“明天去吃火锅吗”
 * 并回复“好啊，明天见！”
 */
public class UDPReceiver02 {
    public static void main(String[] args) throws IOException {
        //接收端使用的端口为9999
        DatagramSocket socket = new DatagramSocket(9999);
        //构建接收的包
        DatagramPacket packet = new DatagramPacket(new byte[1024],1024);
        System.out.println("接收端 等待接收数据...");
        //1. 接收发送端发过来的话，“明天去吃火锅吗”
        socket.receive(packet);
        //关键点！第二个参数是byte的长度不是字符串的长度！
        System.out.println("接收端 收到数据：" + new String(packet.getData(),0,packet.getLength()));
        //2. 并回复“好啊，明天见！”
        String receStr = "好啊！明天见！";
        socket.send(new DatagramPacket(receStr.getBytes(),receStr.getBytes().length, InetAddress.getLocalHost(),9998));
        socket.close();
        System.out.println("接收端退出...");
    }

}
